//socket地址  wss://开头
const socketURL = "wss://apishop.qiancdj.com/websocket";
//链接socket的实例
const app_socket = null;
//心跳计时器
const app_socketHeartTime = null;
//socket重连计时器
const app_socketAgainTime = null;
//存储信息
import storage from "@/utils/storage.js";
import st from "@/utils/showtoast.js";
//重连次数
const reconnetCount = 0;

import {
	bindClientId
} from "../api/newLive";

export default {
	/**
	 * 初始化
	 */
	initSocket() {
		this.connetSocket()
		this.onSocketListenData()
	},
	/**
	 * 链接socket
	 */
	connetSocket() {
		this.app_socket = uni.connectSocket({
			url: socketURL,
			success: succ => {
				console.log('--=succ', succ)
			},
			fail: err => {
				console.log('-=-=err', err)
			},
			complete: () => {}
		})
	},
	/**
	 * 监听数据变化
	 */
	onSocketListenData() {
		//监听 WebSocket 连接打开事件
		this.app_socket.onOpen(res => {
			console.log("链接打开", res);
			clearTimeout(this.app_socketAgainTime)
			this.reconnetCount = 0;
			this.onBing()
		})
		//监听 WebSocket 连接关闭事件
		this.app_socket.onClose(res => {
			console.log("链接关闭", res);
		})
		//监听 WebSocket 错误事件
		this.app_socket.onError(res => {
			console.log("链接错误", res);
			// this.reconnetSocket()
		})
		//监听收到的信息
		this.onReceiveMessage()
	},
	/**
	 * 绑定用户
	 */
	onBing(bindSuccess) {
		const user_id = storage.getUserID()
		if (user_id === "") {
			return
		}
		const message = {
			"uid": user_id + '',
			"type": "bind"
		}
		this.app_socket.send({
			data: JSON.stringify(message),
			success: res => {
				console.log("绑定成功", res);
				if (bindSuccess) {
					bindSuccess()
				}
				this.onSocketHeart()
			},
			fail: res => {
				console.log("绑定失败", res)
			}
		})
	},
	/**
	 * 心跳
	 */
	onSocketHeart() {
		let data = {
			"type": "ping"
		}
		this.app_socketHeartTime = setTimeout(() => {
			this.onSend(data, () => {
				// console.log("心跳发送成功");
				this.onSocketHeart()
			})
		}, 10000)
	},
	/**
	 * 重连
	 */
	reconnetSocket() {
		this.app_socketAgainTime = setInterval(() => {
			if (this.reconnetCount > 10) {
				clearInterval(this.app_socketAgainTime)
				return;
			}
			console.log("重连socket");
			this.connetSocket()
			this.reconnetCount++;
		}, 3000)
	},
	/**
	 * 通过 WebSocket 连接发送数据
	 */
	onSend(message, handler) {
		this.app_socket.send({
			data: JSON.stringify(message),
			success: res => {
				// console.log("发送成功", res);
				handler & handler()
			},
			fail: res => {
				console.log("发送数据失败", res);
			}
		})
	},
	/**
	 * 监听 WebSocket 接受到服务器的消息事件
	 */
	onReceiveMessage() {
		this.app_socket.onMessage(res => {
			let data = JSON.parse(res.data)
			if (data.type !== "ping" || data.type !== "bind") {
				console.log("接收到的消息", res);
			}
			if (data.type == 'bind') {
				bindClientId({
					client_id: data.client_id
				})
				return
			}
			if (data.type === "in_room") { //进入直播间后返回的直播间排行榜
				//保存在本地
				storage.setRoomRankInfo(data)
				this.onNoticeRefresh()
			} else if (data.type === "out_room") { //退出房间
				storage.setRoomRankInfo(data)
				this.onNoticeRefresh()
			} else if (data.type === "send_comment") { //发送消息或者送礼物出现的内容
				uni.$emit("chatInfo", data.data)
			} else if (data.type === "peas") { //用户余额
				uni.$emit("updateBalance", data.data)
			} else if (data.type === "give_gift") { //赠送礼物
				uni.$emit("sendGiftDM", data.data)
			} else if (data.type === "follow") { //关注主播

			} else if (data.type === "up_accept_lianmai") { //主播同意连麦告诉连麦的用户
				if (data.data.pass == 2) {
					return
				}
				let info = storage.getLiveRoomInfo()
				info.url.yh_lurl = data.data.url.yh_lurl
				info.url.yh_turl = data.data.url.yh_turl
				storage.setLiveRoomInfo(info)
				uni.$emit("zbAgreeLMNoticeLMYH", data.data)
			} else if (data.type === "end_lianmai") { //结束连麦
				uni.$emit("onSocketEndLM")
			} else if (data.type === 'kick_out') { // 踢出房间，所有人收到，符合user_id退出
				storage.setRoomRankInfo(data)
				if (storage.getUserID() == data.data.user_id) {
					st.show("您已被踢出直播间", () => {
						uni.$emit("onAndroidBackPress")
						uni.navigateBack()
					})
				}
				this.onNoticeRefresh()
			} else if (data.type === "up_apply_lianmai") { //主播申请用户进行连麦
				uni.$emit("zbApplyYHLM", data.data)
			} else if (data.type === "end_live") { //直播关播了
				st.show("主播已关播", () => {
					uni.$emit("onAndroidBackPress")
					uni.navigateBack()
				})				
			} else if (data.type === "relieve_speak") { //接触禁言了
			
			} else if (data.type === "no_speak") { //被禁言了
				
			}
		})
	},
	/**
	 * 关闭 WebSocket 连接
	 */
	closeSocket() {
		clearTimeout(this.app_socketHeartTime)
		clearTimeout(this.app_socketAgainTime)
		if (this.app_socket) {
			uni.closeSocket()
			this.app_socket = null
		}
	},

	/**
	 * 通知刷新右上角榜单信息
	 */
	onNoticeRefresh() {
		uni.$emit('ZBStartLive')
		uni.$emit('YHStartLook')
		uni.$emit("refreshUserList")
	}
};